namespace RBAC.Write.Api.Application.Handler.ERP.InboundManagement
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.Dto.Output;
    using RBAC.Domain.StorageManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.ERP.InboundManagement;

    public class AppOrUnappPurchaseStorageHandler
        : IRequestHandler<AppOrUnappPurchaseStorageCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<PurchaseStorage> headerRepo;
        private readonly ILogger<AppOrUnappPurchaseStorageHandler> logger;

        public AppOrUnappPurchaseStorageHandler(
            IBaseRepository<PurchaseStorage> headerRepo,
            ILogger<AppOrUnappPurchaseStorageHandler> logger)
        {
            this.headerRepo = headerRepo;
            this.logger = logger;
        }

        public Task<APIResult<bool>> Handle(AppOrUnappPurchaseStorageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>();
            try
            {
                if (request.Id <= 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "无效的主表ID";
                    result.Data = false;
                    return Task.FromResult(result);
                }
                var target = (request.TargetStatus ?? string.Empty).Trim();
                if (target != "开立" && target != "审批")
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "TargetStatus 仅支持：开立/审批";
                    result.Data = false;
                    return Task.FromResult(result);
                }

                // 校验单据存在
                var header = headerRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id });
                if (header == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "单据不存在或已删除";
                    result.Data = false;
                    return Task.FromResult(result);
                }

                var now = DateTime.Now;
                string sql;
                object param;
                if (target == "审批")
                {
                    sql = @"START TRANSACTION;
UPDATE PurchaseStorage SET 
    OrderStatus = @OrderStatus,
    Auditor = @Auditor,
    AuditDate = @AuditDate
WHERE Id = @Id AND IsDeleted = 0;
COMMIT;";
                    param = new { Id = request.Id, OrderStatus = target, Auditor = request.Operator, AuditDate = now };
                }
                else // 开立 -> 反审
                {
                    sql = @"START TRANSACTION;
UPDATE PurchaseStorage SET 
    OrderStatus = @OrderStatus,
    Auditor = NULL,
    AuditDate = NULL
WHERE Id = @Id AND IsDeleted = 0;
COMMIT;";
                    param = new { Id = request.Id, OrderStatus = target };
                }

                try
                {
                    headerRepo.Execute(sql, param);
                }
                catch (Exception)
                {
                    headerRepo.Execute("ROLLBACK;");
                    throw;
                }

                result.Code = APIEnums.Success;
                result.Msg = target == "审批" ? "审批成功" : "反审成功";
                result.Data = true;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "审批/反审失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "审批/反审失败";
                result.Data = false;
            }

            return Task.FromResult(result);
        }
    }
}
